<template>
  <el-card>
    <el-table
      :data="categoryList"
      border
      :row-key="getRowKey"
      lazy
      :load="load"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      ref="categoryRef"
    >
      <el-table-column label="分类id" prop="id" width="150"></el-table-column>
      <el-table-column label="分类名称" prop="name"></el-table-column>
      <el-table-column width="250" align="center">
        <template #header>
          <el-input
            placeholder="按enter添加一级分类"
            v-model="categoryName"
            @keyup.enter="add1Category"
          ></el-input>
        </template>
        <template v-slot="{ row }">
          <el-button
            type="primary"
            :icon="Plus"
            size="small"
            title="添加"
            :disabled="row.level === 3"
            @click="showAddCategory(row)"
          ></el-button>
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            title="修改"
            @click="showUpdateCategory(row)"
          ></el-button>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`您确定要删除${row.name}吗？`"
            @confirm="deleteCategory(row)"
          >
            <template #reference>
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                title="删除"
              />
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加 二/三级 分类 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${isUpdateCategory ? '更新' : '添加'}${
        category.level === 1 ? '二级' : '三级'
      }分类`"
    >
      <el-form>
        <el-form-item label="分类名称">
          <el-input
            placeholder="请输入分类名称"
            v-model="updatedCategory.name"
            v-if="isUpdateCategory"
          />
          <el-input
            placeholder="请输入分类名称"
            v-model="categoryName"
            v-else
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hanldeCancle">取消</el-button>
          <el-button
            type="primary"
            @click="updateCategory"
            v-if="isUpdateCategory"
          >
            确定
          </el-button>
          <el-button type="primary" @click="addCategory" v-else>
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XCategory",
};
</script>

<script lang="ts" setup>
import { Delete, Edit, Plus } from "@element-plus/icons-vue";
import { InfoFilled } from "@element-plus/icons-vue";
import { CategoryList, CategoryItem } from "@/api/product/model/categoryModel";
import { ref, onMounted } from "vue";
import {
  GetCategory1ListApi,
  GetCategory2ListApi,
  GetCategory3ListApi,
  AddCategory1Api,
  AddCategory2Api,
  AddCategory3Api,
  UpdateCategory1Api,
  UpdateCategory2Api,
  UpdateCategory3Api,
  RemoveCategory1Api,
  RemoveCategory2Api,
  RemoveCategory3Api,
} from "@/api/product/category";
import { ElMessage } from "element-plus";

const categoryList = ref<CategoryList>([]);

const getCategory1List = async () => {
  const res = await GetCategory1ListApi();
  categoryList.value = res.map((category) => {
    return {
      ...category,
      // children: []
      hasChildren: true, // 具备子节点
      level: 1,
    };
  });
};

// onMounted(() => {
//   getCategory1List();
// });
onMounted(getCategory1List);

const hanldeCancle = () => {
  dialogVisible.value = false;
  categoryName.value = "";
};

const getRowKey = (row: CategoryItem) => {
  return row.level + "-" + row.id;
};

const load = async (
  row: CategoryItem,
  treeNode: unknown,
  resolve: (date: CategoryList) => void
) => {
  if (row.level === 1) {
    const res = await GetCategory2ListApi(row.id);
    resolve(
      res.map((category) => {
        return {
          ...category,
          hasChildren: true,
          level: 2,
        };
      })
    );
  } else if (row.level === 2) {
    const res = await GetCategory3ListApi(row.id);
    resolve(
      res.map((category) => {
        return {
          ...category,
          level: 3,
        };
      })
    );
  }
};

// 定义添加分类input数据
const categoryName = ref("");
// 添加一级分类
const add1Category = async () => {
  // 输入内容为空，不添加
  if (!categoryName.value) return;
  await AddCategory1Api(categoryName.value);
  ElMessage.success("添加一级分类成功！");
  // 更新数据
  getCategory1List();
  // 清空输入框
  categoryName.value = "";
};

// 显示对话框
const dialogVisible = ref(false);
// 定义添加分类的数据
const category = ref<CategoryItem>({
  id: 0,
  name: "",
});

// 显示添加分类
const showAddCategory = (row: CategoryItem) => {
  isUpdateCategory.value = false;
  dialogVisible.value = true;
  category.value = row;
};

const categoryRef = ref();

// 添加二级或者三级分类
const addCategory = async () => {
  if (!categoryName.value) return;
  if (category.value.level === 1) {
    // 添加二级分类
    await AddCategory2Api(categoryName.value, category.value.id);
  } else if (category.value.level === 2) {
    // 添加三级分类
    await AddCategory3Api(categoryName.value, category.value.id);
  }

  // 找到对应数据，loaded为false代表数据未加载
  categoryRef.value.store.states.treeData.value[
    `${category.value.level}-${category.value.id}`
  ].loaded = false;
  // 触发load，加载渲染对应节点
  categoryRef.value.store.loadOrToggle(category.value);

  ElMessage.success(
    `添加${category.value.level === 1 ? "二级" : "三级"}分类成功！`
  );
  // 复用handleCancle
  hanldeCancle();
};

// 修改分类标识
const isUpdateCategory = ref(false);
// 定义修改分类的数据
const updatedCategory = ref({
  id: 0,
  name: "",
});

// 显示更新分类
const showUpdateCategory = (row: CategoryItem) => {
  isUpdateCategory.value = true;
  dialogVisible.value = true;
  category.value = row;
  updatedCategory.value = {
    ...row,
  };
};

// 点击更新分类
const updateCategory = async () => {
  if (!category.value.name) return;
  if (category.value.level === 1) {
    // 更新一级分类
    await UpdateCategory1Api(category.value.id, category.value.name);
  } else if (category.value.level === 2) {
    // 更新二级分类
    await UpdateCategory2Api(category.value.id, category.value.name);
  } else {
    // 更新三级分类
    await UpdateCategory3Api(category.value.id, category.value.name);
  }
  // 将添加分类数据赋值为更新分类数据
  category.value.name = updatedCategory.value.name;

  ElMessage.success("更新分类成功！");
  hanldeCancle();
};

// 删除分类
const deleteCategory = async (row: CategoryItem) => {
  if (row.level === 1) {
    // 删除一级分类
    await RemoveCategory1Api(row.id);
  } else if (row.level === 2) {
    // 删除二级分类
    await RemoveCategory2Api(row.id);
  } else {
    // 删除三级分类
    await RemoveCategory3Api(row.id);
  }
  // 找到对应数据，loaded为false代表数据未加载
  categoryRef.value.store.states.treeData.value[
    `${category.value.level}-${category.value.id}`
  ].loaded = false;
  // 触发load，加载渲染对应节点
  categoryRef.value.store.loadOrToggle(category.value);
  ElMessage.success(`删除${row.name}成功！`);
};
</script>

<style scoped></style>
